<template>
  <div class="orderTableList">
    <el-card class="box-card"
             shadow="never">
      <!-- 订单查询 -->
      <UserSearch @search="reload"></UserSearch>
      <ele-pro-table ref="table"
                     :columns="columns"
                     :datasource="datasource"
                     :border="false"
                     :disabled="false"
                     :toolbar="false"
                     class="customStyle"
                     default-expand-all
                     cache-key="systemUserTable">
        <!-- 展开内容 -->
        <template v-slot:expand="{ row }">
          <div class="orderrowinfo">
            <span class="orderNumber"> 订单号:{{ row?.orderNumber }}</span>

            <span class="createDate">
              创建时间:{{ toDateString(row?.createdAt) }}</span>

            <span class="buyName">
              买家姓名:{{ row?.addressManagement?.consignee }}</span>
            <span class="iphone">
              买家手机号:{{ row?.addressManagement?.mobile }}</span>
          </div>
        </template>
        <!-- Number(item.packageList?.servicePrice)+ -->
        <template v-slot:servicePrice="{ row }">
          <div v-if="row.orderList?.length">
            <div>
              <!-- +Number(row.packageList?.servicePrice) -->
              ￥{{(overtimePrice(row.packageList?.servicePrice, row.orderList ))}}元
            </div>
            <!-- <div>
              ￥{{Number(row.packageList?.servicePrice) }}元
            </div> -->
          </div>
          <div v-else-if="(!(row.orderList?.length)&&row?.fatherOrderNumber)">
            ￥{{ row.packageList?.plusClockPrice }}元
          </div>
          <div v-else>
            ￥{{ row.packageList?.servicePrice }}元
          </div>
        </template>
        <template v-slot:serviceCategoriesId="{ row }">
          <div style="z-index: 999999999;">
            {{ row.serviceCategories?.classificationName }}
          </div>
        </template>
        <!-- 订单信息 -->
        <template v-slot:orderingInformation="{ row }">
          <div class="realNameStyle flex-start-center">
            <div v-if="row.orderList?.length">
              <div class="display-center">
                <img class="avaterName "
                     :src="row.packageList?.rotationChart?row.packageList?.rotationChart:'https://n8.dns06.com/fd38b968cd6745599b8cf33bd9b6710a.png'"
                     alt="" />
                <div v-if="row.fatherOrderNumber"
                     class="addClock"><span style="color: #fff;font-size: 10px;">加钟</span></div>
                <div v-for="(item,index) in row.orderList"
                     :key="index">
                  <img class="avaterNameAddClock "
                       :src="item.packageList?.rotationChart?item.packageList?.rotationChart:'https://n8.dns06.com/fd38b968cd6745599b8cf33bd9b6710a.png'"
                       alt="" />
                  <div v-if="item.fatherOrderNumber"
                       class="addClocks"><span style="color: #fff;font-size: 10px;">加钟</span></div>
                </div>
              </div>
            </div>
            <div v-else>
              <img class="avaterName "
                   :src="row.packageList?.rotationChart?row.packageList?.rotationChart:'https://n8.dns06.com/fd38b968cd6745599b8cf33bd9b6710a.png'"
                   alt="" />
              <div v-if="row.fatherOrderNumber"
                   class="addClock"><span style="color: #fff;font-size: 10px;">加钟</span></div>
            </div>
            <div class="flex-column-start">
              <div>{{ row.packageList?.tradeName }}</div>
              <div class="technicianName">已选技师:{{ row.technician?.technicianName?row.technician?.technicianName:'--' }}</div>

              <div v-if="row.fatherOrderNumber">当前为订单:<span class="technicianName">{{row.fatherOrderNumber }}</span>的加钟服务</div>
              <div class="technicianName"
                   v-if="row.status == 1 && Number(timestamps(row.createdAt)) - currTime <= 0"><span style="color: red;">已超时</span></div>
            </div>
          </div>
        </template>
        <!-- 信息 -->
        <template v-slot:informations="{ row }">

          <div class="flex-column">
            <el-link v-if="row.refundStatus==1"
                     :underline="false"
                     :type="informationType(row.status)?.types">
              订单状态： {{ informationType(row.status).status }}
            </el-link>
            <el-link v-else
                     :underline="false"
                     type="danger">
              退款中
            </el-link>

            <!-- <el-link :underline="false">
              {{ row.payStatus}}
            </el-link> -->
            <el-link :underline="false"
                     type="primary"
                     @click="viewDetail(row)">
              查看详情
            </el-link>
            <el-link :underline="false"
                     :type="serviceStatusType(row?.payStatus).types">
              支付状态：{{ serviceStatusType(row?.payStatus).status }}
            </el-link>

            <!-- <el-link :underline="false"
                     class="technicianName"
                     @click="visibleModalFn(row)"
                     v-if="row.status == 1 && Number(timestamps(row.createdAt)) - currTime <= 0"><span style="color: red;">取消订单</span></el-link> -->
          </div>

        </template>
        <template v-slot:number="{ row }">

          <div v-if="row.orderList?.length">
            <div>
              <span> {{ Number(row.number)+Number(row.orderList?.length)}}</span>

            </div>
          </div>
          <div v-else>
            {{ row.number }}
          </div>
        </template>

        <template v-slot:payMethod="{ row }">

          <el-link :underline="false"
                   :type="row.payMethod=='1'?'warning':'success'">
            {{ row.payMethod=='1'?'余额支付':'微信支付' }}
          </el-link>
        </template>
        <!-- 服务状态 -->
        <template v-slot:disbursements="{ row }">
          <div class="flex">
            <div>
              <el-link v-if="row?.status == '5'"
                       :underline="false"
                       type="danger">
                {{ row.payStatus=='2'?'取消金额':'退款金额' }}
              </el-link>

              <div v-if="row?.status == '5'">￥ {{ row?.disbursements }}</div>
              <div v-else>
                <div v-if="row.orderList?.length">
                  <div>
                    ￥ {{disbursementsPrice(Number(row?.disbursements),row.orderList) }}元
                  </div>

                </div>
                <div v-else-if="row.fatherOrderNumber&&!(row.orderList?.length)">
                  ￥ {{row?.plusClockPrice }}元
                </div>
                <div v-else>
                  ￥ {{row?.disbursements }}元
                </div>

              </div>
              <div class="flex-column">
                <el-link v-if="row?.status == '5'&& !(row.payStatus=='2')"
                         :underline="false"
                         type="danger">
                  实际退款
                </el-link>

                <!-- <div style="color: red;"
                     v-if="row?.status == '5'&& !(row.payStatus=='2')">
                  ￥ {{row?.expensesIncurred?((Math.floor((row.disbursements-((((row.refundRate))?((row.refundRate)):0)* row.disbursements  )/100) * 100) / 100).toFixed(2)-row?.expensesIncurred).toFixed(2) :(Math.floor((row.disbursements-((((row.refundRate))?((row.refundRate)):0)* row.disbursements  )/100) * 100) / 100).toFixed(2) }}
                </div> -->
                <div style="color: red;"
                     v-if="row?.status == '5'&& !(row.payStatus=='2')">
                  ￥ {{row.refundAmount?row.refundAmount:0 }}
                </div>
                <!-- <div style="color: red;"
                     v-if="row?.status == '5' && row?.expensesIncurred">
                  ￥ {{(Math.floor((row.disbursements-((((row.refundRate))?((row.refundRate)):0)* row.disbursements  )/100) * 100) / 100).toFixed(2) }}
                </div> -->
              </div>
              <div class="flex-column">
                <el-link v-if=" row.status != 5&&row?.deductionAmount!=='0.00'"
                         :underline="false"
                         type="primary">
                  （使用{{ integralName?integralName:'积分' }}:{{row.pointsUsed?row?.pointsUsed:'0'  }} 和优惠劵 {{cardCoupon(row?.pointsUsed,row?.deductionAmount)}}元抵扣
                  {{ row?.deductionAmount ? row.deductionAmount : '0' }}元）

                </el-link>
                <el-link v-if=" row?.expensesIncurred!=='0.00'"
                         :underline="false"
                         type="primary">

                  出行费用:{{row?.expensesIncurred?row?.expensesIncurred:0  }}元
                </el-link>
                <el-link v-if="row.status == 5&&row?.deductionAmount!=='0.00'"
                         :underline="false"
                         type="primary">
                  （已退{{ integralName?integralName:'积分' }}:{{row.pointsUsed?row?.pointsUsed:'0'  }} 和优惠劵 {{cardCoupon(row?.pointsUsed,row?.deductionAmount)}}元一共
                  {{ row?.deductionAmount ? row.deductionAmount : '0' }}元）

                </el-link>
              </div>
            </div>

            <!-- <div>
              <el-link @click="partialRefund(row)"
                       style="color: red; margin-left: 10px;"
                       :underline="false">
                部分退款
              </el-link>
            </div> -->
          </div>
        </template>

        <!-- 操作 -->

      </ele-pro-table>
    </el-card>
    <drawerOrderInfo :data="current"
                     :drawerOrderInfo.sync="drawerEditBoolen"></drawerOrderInfo>
    <ele-modal width="600px"
               height="300px"
               title="退款说明"
               :visible.sync="visibleModal"
               :maxable="true">
      <!-- class="SigningReminder" -->

      <el-input type="textarea"
                v-model="refundInstructions"
                maxlength="500"
                show-word-limit
                resize="none"
                class="textarea-box"></el-input>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="visibleModal=false">取 消</el-button>
        <el-button type="primary"
                   @click="visibleModalFn()">确定</el-button>

      </span>
    </ele-modal>
  </div>
</template>
<script>
import {

  sitePlatformConfigDetail,
  refundIst

} from '@/api/basicConfiguration/platformConfiguration';
import UserSearch from '../components/user-search.vue';
import moment from 'moment';
import {
  orderList,
  orderDetail
} from '@/api/orderManagement/orderList/index';
import drawerOrderInfo from '../components/drawerOrderInfo.vue';
import { orderTableList } from '../constant/constant';
export default {
  name: 'orderTableList',
  components: { drawerOrderInfo, UserSearch },
  data () {
    return {
      totelPrice: 0,
      toteldisbursementsPrice: 0,
      orderTableList,
      //  技能评分
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      value: 4,
      current: null,
      visibleModal: false,
      currTime: new Date().getTime(),
      // 表格列配置
      columns: [
        {
          width: 5,
          type: 'expand',
          columnKey: 'expand',
          align: 'center',
          slot: 'expand'
        },

        // {
        //   columnKey: 'index',
        //   type: 'index',
        //   label: '序号',
        //   width: 40,
        //   align: 'center',
        //   showOverflowTooltip: true,
        //   fixed: 'left'
        // },
        // {
        //   columnKey: 'selection',
        //   type: 'selection',
        //   width: 45,
        //   align: 'center',
        //   fixed: 'left'
        // },

        {
          prop: 'orderingInformation',
          label: '订单信息',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 180,
          slot: 'orderingInformation'
        },
        {
          prop: 'serviceCategoriesId',
          label: '类目',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 160,
          slot: 'serviceCategoriesId',

        },
        {
          prop: 'servicePrice',
          label: '价格',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110,
          slot: 'servicePrice'
        },

        {
          prop: 'number',
          label: '数量',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 150,
          slot: 'number'
        },

        {
          prop: 'payMethod',
          label: '支付方式',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110,
          slot: 'payMethod'
        },
        {
          prop: 'informations',
          label: '信息',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 150,
          slot: 'informations'
        },
        {
          prop: 'disbursements',
          label: '实付款',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 150,
          slot: 'disbursements'
        }
        // {
        //   columnKey: 'action',
        //   label: '操作',
        //   width: 320,
        //   align: 'center',
        //   resizable: false,
        //   slot: 'action',
        //   showOverflowTooltip: true,

        //   fixed: 'right'
        // }
      ],
      // 表格选中数据
      selection: [],
      integralName: '',
      drawerEditBoolen: false,
      // 订单列表信息
      orderListInformation: null,
      //  退款说明
      refundInstructions: ''
    };
  },

  computed: {

    overtimePrice: function () {
      return function (zhuSum, projectList) {
        let sum = '';
        let fitSum = 0;
        for (let i = 0; i < projectList.length; i++) {

          fitSum += Number(projectList[i].plusClockPrice);

        }
        // console.log('fitSum', fitSum);
        sum = Number(zhuSum) + fitSum;
        // console.log(sum)
        return Number(sum).toFixed(2);
      };
    },
    timestamps: function () {
      return function (day) {
        let timestamps = '';
        /* let time = day.split('T')[0] + ' ' + day.split('T')[1];
          timestamps = new Date(time).getTime(); */
        timestamps = new Date(day).getTime();
        timestamps = timestamps + 3600 * 1000 * 1; // 在下单时间的基础上，加一小时
        // console.log('timestamps======', timestamps);
        return timestamps;
      };
    },
    disbursementsPrice () {
      return function (zhuSum, projectList) {
        let sum = '';
        let fitSum = 0;
        for (let i = 0; i < projectList.length; i++) {

          fitSum += Number(projectList[i].plusClockPrice);

        }
        // console.log('fitSum', fitSum);
        sum = Number(zhuSum) + fitSum;
        // console.log(sum)
        return Number(sum).toFixed(2);
      };


    },
    // 卡券余额
    cardCoupon () {
      return function (pointsUsed, deductionAmount) {

        let pointsUseds = pointsUsed ? pointsUsed : 0
        let deductionAmounts = Number(deductionAmount) ? Number(deductionAmount) : 0
        if (deductionAmounts >= pointsUseds) {
          const cardCoupon = deductionAmounts - pointsUseds

          return cardCoupon
        } else {
          return 0
        }
      }
    },
    toDateString () {
      return function (originalDateStr) {
        const date = moment(originalDateStr);
        const formattedDate = date.format('YYYY-MM-DD HH:mm');
        return formattedDate;
      };
    },
    // 是否开启响应式布局
    styleResponsive () {
      return this.$store.state.theme.styleResponsive;
    },
    // 服务状态
    serviceStatusType () {
      return function (serviceType) {

        if (serviceType == 1) {
          return {
            status: '已支付',
            types: 'success'
          };
        } else if (serviceType == 2) {
          return {
            status: '未支付',
            types: 'warning'
          };
        } else if (serviceType == 3) {
          return {
            status: '退款',
            types: 'danger'
          };
        } else {
          return {
            status: '状态为null',
            types: 'danger'
          };
        }
      };
    },
    // 实名认证
    informationType () {
      return function (informationType) {

        if (informationType == 0) {
          return {
            status: '待付款',
            types: 'danger'
          };
        } else if (informationType == 1) {
          return {
            status: '待接单',
            types: 'warning'
          };
        } else if (informationType == 2) {
          return {
            status: '已接单',
            types: 'success'
          };
        } else if (informationType == 3) {
          return {
            status: '服务中',
            types: 'success'
          };
        } else if (informationType == 4) {
          return {
            status: '已经完成',
            types: 'success'
          };
        } else if (informationType == 5) {
          return {
            status: '已取消/退款',
            types: 'danger'
          };
        }
      };
    }
  },
  activated () {
    this.init()
    this.reload()
  },
  methods: {

    async visibleModalFn (row) {
      this.visibleModal = !this.visibleModal
      //   console.log(this.orderListInformation)
      const res = await refundIst({
        siteId: this.$store.state.site.info.id, // 站点id
        userId: row.userId, //登录用户的id
        // 订单id
        orderId: row.id,
        // 订单编号
        orderNumber: row.orderNumber,
        // 退款金额 = 实付款 + 已经扣除的手续费
        //   refundAmount: refundAmount,
        // 实付款 
        disbursements: Number(row.disbursements),
        // 退款流程 (1.提交申请 2.审核通过 3.退款成功 )
        refundProcess: 1, // 默认传1
        // 退款数量
        number: row.number,
        // 退款原因
        refund: '其他',
        // 退款说明
        refundInstructions: row.refundInstructions,
        // 退款凭证
        refundVoucher: '', //图片，最多九张用英文逗号隔开
        // 服务/订单状态  1.待接单 2.已接单（待服务） 3.服务中 4.已完成 5.已取消/退款
        status: 1
      })

      console.log(res)
      if (res.code == 200) {
        this.$message.success('退款成功')
        this.reload();

      } else {
        this.$message.success('退款失败')
      }
    },
    //  部分退款
    // partialRefund (row) {


    //   console.log(row)
    //   this.orderListInformation = row
    //   this.visibleModal = !this.visibleModal
    //   //refundIst
    // },
    async init () {
      const res = await sitePlatformConfigDetail()
      //   console.log(res)
      if (res) {
        this.integralName = res.integralName
      }
    },
    // 点击查看详情弹出详情抽屉
    async viewDetail (row) {
      if (row) {
        // const res = await orderDetail(row.id)
        // console.log(res)
        this.current = row;
        // 用户余额管理
        this.drawerEditBoolen = !this.drawerEditBoolen;
      } else {
        this.drawerEditBoolen = !this.drawerEditBoolen;
        this.current = null;
      }
    },

    /* 表格数据源 */
    async datasource ({ page, limit, where, order }) {
      if (!where.deleted);

      // 这里需要进行判断 如果有加套餐 需要根据  fatherOrderNumber 变成一条数据
      const res = await orderList({
        page,
        limit,
        ...where,
        siteId: this.$store.state.site.info.id
      });
      console.log(res)
      return res
    },
    /* 刷新表格 */
    reload (where) {
      this.$refs.table.reload({ page: 1, where: where, types: 1 });
    },

    /* 删除 */
    remove (row) {
      const loading = this.$loading({ lock: true });
      mealDelete({ ids: [row.id] })
        .then((msg) => {
          loading.close();
          this.$message.success(msg);
          this.reload();
        })
        .catch((e) => {
          loading.close();
          this.$message.error(e.message);
        });
    },
    /* 批量删除 */
    removeBatch () {
      if (!this.selection.length) {
        this.$message.error('请至少选择一条数据');
        return;
      }
      this.$confirm('确定要删除选中的套餐吗?', '提示', {
        type: 'warning'
      })
        .then(() => {
          const loading = this.$loading({ lock: true });
          removeMeal({ ids: this.selection.map((d) => d.id) })
            .then((msg) => {
              loading.close();
              this.$message.success(msg);
              this.reload();
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
        })
        .catch(() => { });
    }
  }
};
</script>
<style lang="less" scoped>
.orderTableList {
  /deep/ .el-table--medium .el-table__cell {
    border: none !important;
  }
  /deep/ .el-icon-arrow-right:before {
    display: none;
  }
  /deep/ .el-textarea__inner {
  }
  .realNameStyle {
    .avaterName {
      width: 74px;
      height: 74px;

      vertical-align: middle;
      margin-right: 5px;
      position: relative;
    }
    .addClock {
      position: absolute;
      top: 10px;

      width: 30px;
      height: 24px;
      background-color: #1890ff;
    }
    .avaterNameAddClock {
      width: 74px;
      height: 74px;

      vertical-align: middle;
      margin-right: 5px;
      position: relative;
    }
    .addClocks {
      position: relative;
      top: -74px;

      width: 30px;
      height: 24px;
      background-color: #1890ff;
    }
    .technicianName {
      color: #1890ff;
      font-size: 12px;
      font-style: normal;
      font-weight: 400;
    }
  }
  .orderrowinfo {
    width: 100%;
    display: flex;
    min-width: 1000px;
    padding: 30px;
    height: 50px;
    align-items: center;
    justify-content: flex-start;
    background-color: #f8f8f8;
    border-bottom: 5px solid rgb(235, 233, 233) !important;
    .orderNumber,
    .createDate,
    .buyName,
    .iphone {
      margin-right: 40px;
      color: #000;
      font-family: Inter;
      font-size: 14px;
      font-style: normal;
      font-weight: 400;
      margin-left: 15px;
    }
  }
}
</style>
